import {Pipe, PipeTransform} from '@angular/core';


@Pipe({
    name: 'numberToChn',
})
export class NumberToChnPipe implements PipeTransform {

    private chnNumChar: string[] = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    private chnUnitSection: string[] = ["", "万", "亿", "万亿", "亿亿"];
    private chnUnitChar: string[] = ["", "十", "百", "千"];


    transform(value: number) {
        return this.TransformToChinese(value);
    }

    private numToChn(num: number) :string{
        let index = num.toString().indexOf(".");
        if (index != -1) {
            let str = num.toString().slice(index);
            let a = "点";
            for (let i = 1; i < str.length; i++) {
                a += this.chnNumChar[parseInt(str[i])];
            }
            return a;
        } else {
            return '';
        }
    }

    //定义在每个小节的内部进行转化的方法，其他部分则与小节内部转化方法相同
    private sectionToChinese(section: number): string {
        let str = '', chnstr = '', zero = false, count = 0;   //zero为是否进行补零， 第一次进行取余由于为个位数，默认不补零
        while (section > 0) {
            let v = section % 10;  //对数字取余10，得到的数即为个位数
            if (v == 0) {                    //如果数字为零，则对字符串进行补零
                if (zero) {
                    zero = false;        //如果遇到连续多次取余都是0，那么只需补一个零即可
                    chnstr = this.chnNumChar[v] + chnstr;
                }
            } else {
                zero = true;           //第一次取余之后，如果再次取余为零，则需要补零
                str = this.chnNumChar[v];
                str += this.chnUnitChar[count];
                chnstr = str + chnstr;
            }
            count++;
            section = Math.floor(section / 10);
        }
        return chnstr;
    }


    private TransformToChinese(num: number): string {
        debugger
        let a = this.numToChn(num);
        num = Math.floor(num);
        let unitPos = 0;
        let strIns = '', chnStr = '';
        let needZero = false;

        if (num === 0) {
            return this.chnNumChar[0];
        }
        while (num > 0) {
            let section = num % 10000;
            if (needZero) {
                chnStr = this.chnNumChar[0] + chnStr;
            }
            strIns = this.sectionToChinese(section);
            strIns += (section !== 0) ? this.chnUnitSection[unitPos] : this.chnUnitSection[0];
            chnStr = strIns + chnStr;
            needZero = (section < 1000) && (section > 0);
            num = Math.floor(num / 10000);
            unitPos++;
        }

        return chnStr + a;
    }

}
